<template>
  <el-dialog :title="title" :visible.sync="visible" width="700px" @close="handleCancel">
    <el-form :model="localFormData" ref="orderForm" label-width="120px" label-position="left">
      <!-- 始发地企业 -->
      <el-form-item label="始发地企业" prop="startCompanyId"
        :rules="[{ required: true, message: '请选择始发地企业', trigger: 'change' }]">
        <el-select v-model="localFormData.startCompanyId" filterable placeholder="请选择企业" clearable
          :disabled="isViewMode">
          <el-option v-for="company in companies" :key="company.companyUuid" :label="company.companyName"
            :value="company.companyUuid">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="卸货地址" prop="desAddress">
        <el-input v-model="localFormData.desAddress" placeholder="请输入卸货地址" />
      </el-form-item>
      <el-form-item label="装卸费（元)" prop="loadUnloadFee"
        :rules="[{ required: true, message: '请输入装卸费金额', trigger: 'blur' }]">
        <el-input v-model="localFormData.loadUnloadFee" placeholder="请输入装卸费" />
      </el-form-item>
      <el-form-item label="回单是否已经收齐" prop="isReceiptReceivedAll"
        :rules="[{ required: true, message: '请选择是否已经收齐状态', trigger: 'change' }]">
        <el-select v-model="localFormData.isReceiptReceivedAll" placeholder="请选择是否已经收齐状态" clearable
          :disabled="isViewMode">
          <el-option v-for="option in getOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="支付给驾驶员日期" prop="offeredData">
        <el-date-picker clearable v-model="localFormData.offeredData" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择支付给驾驶员日期">
        </el-date-picker>
      </el-form-item>
      <!-- 目的地企业 -->
      <el-form-item label="目的地企业" prop="desCompanyIds">
        <el-select v-model="localFormData.desCompanyIds" filterable multiple placeholder="请选择企业" clearable
          :disabled="isViewMode">
          <el-option v-for="company in companies" :key="company.companyUuid" :label="company.companyName"
            :value="company.companyUuid">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 运输人员 -->
      <el-form-item label="运输人员" prop="transportId"
        :rules="[{ required: true, message: '请选择运输人员', trigger: 'change' }]">
        <el-select v-model="localFormData.transportId" filterable placeholder="请选择运输人" clearable :disabled="isViewMode">
          <el-option v-for="driver in drivers" :key="driver.driverUuid" :label="driver.driverName"
            :value="driver.driverUuid">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 载货量 -->
      <el-form-item label="载货量(吨)" prop="cargoCapacity"
        :rules="[{ required: true, message: '请输入载货量', trigger: 'blur' }]">
        <el-input type="number" v-model="localFormData.cargoCapacity" placeholder="请输入载货量" min="0"
          :disabled="isViewMode" />
      </el-form-item>

      <!-- 企业金额 -->
      <el-form-item label="企业金额(元)" prop="companyOffer"
        :rules="[{ required: true, message: '请输入企业金额', trigger: 'blur' }]">
        <el-input type="number" v-model="localFormData.companyOffer" placeholder="请输入企业金额" min="0" step="0.01"
          :disabled="isViewMode" />
      </el-form-item>

      <!-- 驾驶员金额 -->
      <el-form-item label="驾驶员金额(元)" prop="driverOffer"
        :rules="[{ required: true, message: '请输入驾驶员金额', trigger: 'blur' }]">
        <el-input type="number" v-model="localFormData.driverOffer" placeholder="请输入驾驶员金额" min="0" step="0.01"
          :disabled="isViewMode" />
      </el-form-item>
      <!-- 驾驶员金额 -->
      <el-form-item label="已支付给驾驶员金额(元)" prop="hasOfferToDriver"
        :rules="[{ required: true, message: '请输入驾驶员金额', trigger: 'blur' }]">
        <el-input type="number" v-model="localFormData.hasOfferToDriver" placeholder="请输入驾驶员金额" min="0" step="0.01"
          :disabled="isViewMode" />
      </el-form-item>

      <!-- 订单开始日期 -->
      <el-form-item label="订单开始日期" prop="orderStartTime"
      :rules="[{ required: true, message: '请输入订单开始日期', trigger: 'blur' }]">
        <el-date-picker v-model="localFormData.orderStartTime" type="date" placeholder="选择开始日期" style="width: 100%;"
          :disabled="isViewMode" />
      </el-form-item>

      <!-- 订单结束日期 -->
      <el-form-item label="订单结束日期" prop="orderEndTime">
        <el-date-picker v-model="localFormData.orderEndTime" type="date" placeholder="选择结束日期" style="width: 100%;"
          :disabled="isViewMode" />
      </el-form-item>

      <!-- 是否已支付给驾驶员 -->
      <el-form-item label="是否已支付给驾驶员(装卸费+驾驶员基本运费)" prop="isOfferedToDriver"
        :rules="[{ required: true, message: '请选择支付状态', trigger: 'change' }]">
        <el-select v-model="localFormData.isOfferedToDriver" placeholder="请选择支付状态" clearable :disabled="isViewMode">
          <el-option v-for="option in paymentOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="localFormData.remark" placeholder="请输入备注" :readonly="isViewMode" />
      </el-form-item>

      <!-- 附件上传       -->
      <el-form-item label="附件" prop="attachments">
        <el-upload class="upload-demo" :action="uploadUrl" name="file" list-type="text" :on-preview="handlePreview"
          :file-list="localFormData.attachments" :on-success="handleUploadSuccess" :on-remove="handleRemoveFile"
          :before-upload="beforeUpload" multiple :on-exceed="handleExceed" :limit="10" :accept="acceptedFileTypes"
          :disabled="isViewMode">
          <el-button type="primary" size="small" icon="el-icon-upload" v-if="!isViewMode">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">支持上传 Word, PDF, 图片, PPT 等格式的文件，单个文件不超过 10MB</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <PreviewModal v-model="showPreviewModal" :url="currentPreviewUrl" />
    <div slot="footer" class="dialog-footer" v-if="!isViewMode">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { selectAllCompanylist } from "@/api/fincal/company";
import { selectAllDriverlist } from "@/api/fincal/driver";
import { addOrder, updateOrder } from "@/api/fincal/order";
import PreviewModal from "@/components/PreviewModal/PreviewModal.vue";

export default {
  name: "OrderDialog",
  components: {
    PreviewModal
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: "新增订单"
    },
    mode: {
      type: String,
      default: "add"
    },
    formData: {
      type: Object,
      default: () => ({
        id: "",
        startCompanyId: "",
        desCompanyIds: [],
        desCompanyId: "",
        transportId: "",
        cargoCapacity: "0",
        companyOffer: "0",
        driverOffer: "0",
        hasOfferToDriver: "0",
        orderStartTime: "",
        orderEndTime: "",
        isOfferedToDriver: "",
        remark: "",
        isReceiptReceivedAll: "0",
        loadUnloadFee: "0",
        desAddress: "",
        offeredData: "",
        attachments: []
      })
    }
  },
  data() {
    return {
      localFormData: {
        id: "",
        startCompanyId: "",
        desCompanyIds: [],
        desCompanyId: "",
        transportId: "",
        cargoCapacity: "0",
        companyOffer: "0",
        driverOffer: "0",
        hasOfferToDriver: "0",
        orderStartTime: "",
        orderEndTime: "",
        isOfferedToDriver: "",
        remark: "",
        isReceiptReceivedAll: "0",
        loadUnloadFee: "0",
        desAddress: "",
        offeredData: "",
        attachments: []
      },
      companies: [],
      //预览窗口
      showPreviewModal: false,
      //预览url
      currentPreviewUrl: "",
      //驾驶员下拉框数据
      drivers: [],
      paymentOptions: [
        { value: "1", label: "是" },
        { value: "0", label: "否" }
      ],
      getOptions: [
        { value: "1", label: "已收齐" },
        { value: "0", label: "未收齐" }
      ],
      uploadUrl: `${process.env.VUE_APP_BASE_API}/file/upload/minio`,
      acceptedFileTypes: ".doc,.docx,.pdf,.jpg,.jpeg,.png,.gif,.ppt,.pptx"
    };
  },
  computed: {
    isViewMode() {
      return this.mode === 'view';
    }
  },
  watch: {
    async visible(val) {
      if (val) {
        await this.loadCompanies();
        await this.loadDrivers();
        if (this.mode === 'edit') {
          this.fetchOrderDetails();
        } else {
          this.resetLocalForm();
        }
      }
    }
  },
  methods: {
    // 处理文件预览（点击图片或其他文件进行预览）
    async handlePreview(file) {
      const baseUrl = process.env.VUE_APP_API_BASE_URL;
      // 读取基础URL
      const fullUrl = `${baseUrl}${file.url}`;
      this.currentPreviewUrl = fullUrl;
      this.showPreviewModal = true;
      await this.$nextTick();

    },
    fetchOrderDetails() {
      this.localFormData = this.formData;
    },
    /** 加载企业列表 */
    loadCompanies() {
      selectAllCompanylist()
        .then(response => {
          this.companies = response.data;
        })
        .catch(error => {
          this.$message.error("加载企业列表失败");
          console.error(error);
        });
    },
    /** 加载驾驶员列表 */
    loadDrivers() {
      selectAllDriverlist()
        .then(response => {
          this.drivers = response.data;
        })
        .catch(error => {
          this.$message.error("加载驾驶员列表失败");
          console.error(error);
        });
    },
    /** 提交表单 */
    handleSubmit() {
      if(this.localFormData.orderStartTime!="" && this.localFormData.orderStartTime){
        this.localFormData.orderStartTime = new Date(this.localFormData.orderStartTime);
      }
      if(this.localFormData.orderEndTime!="" && this.localFormData.orderEndTime){
        this.localFormData.orderEndTime = new Date(this.localFormData.orderEndTime);
      }
      this.localFormData.desCompanyId = this.localFormData.desCompanyIds.join(',');
      this.$refs.orderForm.validate((valid) => {
        const payload = { ...this.localFormData };
        // 处理日期格式
        payload.orderStartTime = this.formatDate(payload.orderStartTime);
        payload.orderEndTime = this.formatDate(payload.orderEndTime);
        if (valid) {
          if (this.mode === 'add') {
            // 新增订单
            addOrder(payload)
              .then(() => {
                this.$message.success("新增成功");
                this.$emit("submit");
                this.handleCancel();
              })
              .catch(() => {
                this.$message.error("新增失败");
              });
          }
          else if (this.mode === 'edit') {
            // 修改订单
            updateOrder(payload)
              .then(() => {
                this.$message.success("修改成功");
                this.$emit("submit");
                this.handleCancel();
              })
              .catch(() => {
                this.$message.error("修改失败");
              });
          }
        } else {
          this.$message.error("请正确填写表单");
          return false;
        }
      });
    },
    /** 取消操作 */
    handleCancel() {
      this.$emit("update:visible", false);
      this.$emit('update:mode', "");
      this.resetLocalForm();
    },
    /** 重置本地表单数据 */
    resetLocalForm() {
      this.localFormData = {
        id: "",
        startCompanyId: "",
        desCompanyIds: [],
        desCompanyId: "",
        transportId: "",
        cargoCapacity: "0",
        companyOffer: "0",
        driverOffer: "0",
        hasOfferToDriver: "0",
        orderStartTime: "",
        orderEndTime: "",
        isOfferedToDriver: "",
        remark: "",
        isReceiptReceivedAll: "0",
        loadUnloadFee: "0",
        desAddress: "",
        offeredData: "",
        attachments: []
      };
      if (this.$refs.orderForm) {
        this.$refs.orderForm.resetFields();
      }
    },
    /** 格式化日期 */
    formatDate(date) {
      if (!date) return "";  // 如果传入的日期无效，返回空字符串
      const d = new Date(date);
      if (isNaN(d.getTime())) {
        return "";  // 如果日期无效，返回空字符串
      }
      const year = d.getFullYear();
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    }
    ,
    /** 上传成功 */
    handleUploadSuccess(response, file, fileList) {
      if (response.code == "200") {
        this.localFormData.attachments.push({
          "url": response.data,
          "name": file.name
        });
        this.$message.success(`${file.name} 上传成功`);
      } else {
        this.$message.error(`${file.name} 上传失败: ${response.message || '未知错误'}`);
      }
    },
    /** 删除上传的文件 */
    handleRemoveFile(file, fileList) {
      if (this.mode === "add") {
        this.localFormData.attachments = this.localFormData.attachments.filter(el => el.name !== file.name);
      } else if (this.mode === "edit") {
        console.log(file);
        console.log(fileList);
        this.localFormData.attachments = this.localFormData.attachments.filter(el => el.name !== file.name);
      }

    },
    /** 上传前的校验 */
    beforeUpload(file) {
      const isAllowedType = this.acceptedFileTypes.includes(file.type) || this.acceptedFileTypes.includes(`.${file.name.split('.').pop().toLowerCase()}`);
      if (!isAllowedType) {
        this.$message.error('不支持的文件类型!');
        return false;
      }
      const isLt4M = file.size / 1024 / 1024 < 4;
      if (!isLt4M) {
        this.$message.error('上传文件大小不能超过 4MB!');
      }
      return isAllowedType && isLt4M;
    },
    // 上传文件超过个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    }
  }
};
</script>

<style scoped>
.upload-demo {
  display: flex;
  flex-direction: column;
}

.dialog-footer {
  text-align: right;
}

/* 自定义文件列表图标 */
.el-upload-list__item-thumbnail {
  display: none;
  /* 隐藏默认的缩略图 */
}

.el-upload-list__item-name {
  display: flex;
  align-items: center;
}

.el-upload-list__item-name::before {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 8px;
  background-size: cover;
  background-repeat: no-repeat;
}

/* 根据文件类型显示不同的图标 */
.el-upload-list__item--text.doc::before {
  background-image: url('~@/assets/icons/file/word.png');
  /* 替换为实际图标路径 */
}

.el-upload-list__item--text.docx::before {
  background-image: url('~@/assets/icons/file/word.png');
  /* 替换为实际图标路径 */
}

.el-upload-list__item--text.pdf::before {
  background-image: url('~@/assets/icons/file/pdf.png');
  /* 替换为实际图标路径 */
}

.el-upload-list__item--text.jpg::before,
.el-upload-list__item--text.jpeg::before,
.el-upload-list__item--text.png::before,
.el-upload-list__item--text.gif::before {
  background-image: url('~@/assets/icons/file/file.png');
  /* 替换为实际图标路径 */
}

.el-upload-list__item--text.ppt::before,
.el-upload-list__item--text.pptx::before {
  background-image: url('~@/assets/icons/file/file.png');
  /* 替换为实际图标路径 */
}
</style>